<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>Delphi websockets demo</title>
		<script type="text/javascript">
			// Websocket status values
			const rsConnecting = 0;
			const rsOpen = 1;
			const rsClosed = 2;

			// Websocket object
			var ws = null;

			// Helper functions
			function $() { 
				return document.getElementById(arguments[0]); 
			}

			function logMsg(msg) { 
				$('txtChatMain').value += msg + '\n'; 
			}

			function enableInputs(val) {
				$('txtChatMsg').readOnly = ! val;
				$('btnChatSend').disabled = ! val;
			}

			function sendMsg(msg) {
				ws.send(msg);
			}

			function btnChatSendClick() {
				var msg = $('txtChatMsg').value;
				if (msg) {
					sendMsg(msg);
					$('txtChatMsg').value = '';
				}
			}

			// Websocket functions
			function connectWebSocket() {
				if ("WebSocket" in window) {
					// Create new websocket connection
					ws = new WebSocket("ws://localhost:7000/");

					// Called after connection is established
					ws.onopen = function() {
						enableInputs(true);
						logMsg('Connected to: ' + ws.URL);
						sendMsg('Hello!');
					};

					// Called when a new message is received
					ws.onmessage = function (msg) { 
						if (msg.data) {
							logMsg(msg.data);
						}
					};

					// Called when connection is closed
					ws.onclose = function() { 
						enableInputs(false);
						logMsg("Connection closed!"); 
					};
				} else {
					logMsg('Browser doesn\'t support websockets!');
				}
			}
		</script>
		<style type='text/css'>
			div#divChat { width:30em; }
			textarea.txtarea { float:left; width: 30em; height: 15em;}
			input.txt { float:left; display: inline; width: 26em; }
			input.btn { float:left; display: inline; width: 4em; }
		</style>
	</head>
	<body onLoad="connectWebSocket();">
		<h2>Delphi websockets chat demo</h2>
		<div id="divChat">
			<textarea name="txtChatMain" id="txtChatMain" readonly="readonly" class="txtarea"></textarea>
			<!-- Inputs are disabled by default -->
			<input type="text" name="txtChatMsg" id="txtChatMsg" readonly="readonly" class="txt" />
			<input type="button" name="btnChatSend" id="btnChatSend" value="Send" onClick="btnChatSendClick();" disabled="disabled" class="btn" />
		</div>
	</body>
</html>
